package logger

import (
	"fmt"
	"os"
	"path/filepath"
	"time"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

var Logger *zap.Logger
var SugarLogger *zap.SugaredLogger

// InitLogger 初始化日志系统
func InitLogger(logPath string, level string) error {
	// 确保日志目录存在
	logDir := filepath.Dir(logPath)
	if err := os.MkdirAll(logDir, 0755); err != nil {
		return fmt.Errorf("创建日志目录失败: %v", err)
	}

	// 日志分割配置
	logWriter := &lumberjack.Logger{
		Filename:   logPath,
		MaxSize:    100,  // MB
		MaxBackups: 30,   // 保留30个备份
		MaxAge:     7,    // 天
		Compress:   true, // 压缩
	}

	// 编码器配置
	encoderConfig := zapcore.EncoderConfig{
		TimeKey:        "time",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		FunctionKey:    zapcore.OmitKey,
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.CapitalLevelEncoder,
		EncodeTime:     customTimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}

	// 设置日志级别
	var zapLevel zapcore.Level
	switch level {
	case "debug":
		zapLevel = zapcore.DebugLevel
	case "info":
		zapLevel = zapcore.InfoLevel
	case "warn":
		zapLevel = zapcore.WarnLevel
	case "error":
		zapLevel = zapcore.ErrorLevel
	default:
		zapLevel = zapcore.InfoLevel
	}

	// 创建核心
	core := zapcore.NewTee(
		// 文件输出
		zapcore.NewCore(
			zapcore.NewJSONEncoder(encoderConfig),
			zapcore.AddSync(logWriter),
			zapLevel,
		),
		// 控制台输出
		zapcore.NewCore(
			zapcore.NewConsoleEncoder(encoderConfig),
			zapcore.AddSync(os.Stdout),
			zapLevel,
		),
	)

	// 创建Logger
	Logger = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
	SugarLogger = Logger.Sugar()

	return nil
}

// 自定义时间格式
func customTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
	enc.AppendString(t.Format("2006-01-02 15:04:05"))
}

// 审计日志结构
type AuditLog struct {
	UserID    uint   `json:"userId"`
	Username  string `json:"username"`
	Action    string `json:"action"`
	Resource  string `json:"resource"`
	IP        string `json:"ip"`
	UserAgent string `json:"userAgent"`
	Details   string `json:"details,omitempty"`
}

// LogAudit 记录审计日志
func LogAudit(log AuditLog) {
	if SugarLogger != nil {
		SugarLogger.Infow("AUDIT",
			"userId", log.UserID,
			"username", log.Username,
			"action", log.Action,
			"resource", log.Resource,
			"ip", log.IP,
			"userAgent", log.UserAgent,
			"details", log.Details,
		)
	}
}

// Info 记录信息日志
func Info(msg string, fields ...interface{}) {
	if SugarLogger != nil {
		SugarLogger.Infow(msg, fields...)
	}
}

// Error 记录错误日志
func Error(msg string, fields ...interface{}) {
	if SugarLogger != nil {
		SugarLogger.Errorw(msg, fields...)
	}
}

// Warn 记录警告日志
func Warn(msg string, fields ...interface{}) {
	if SugarLogger != nil {
		SugarLogger.Warnw(msg, fields...)
	}
}

// Debug 记录调试日志
func Debug(msg string, fields ...interface{}) {
	if SugarLogger != nil {
		SugarLogger.Debugw(msg, fields...)
	}
}

// Sync 刷新日志
func Sync() {
	if Logger != nil {
		_ = Logger.Sync()
	}
}
